#!/usr/bin/env python
# -*- coding: utf-8 -*-


import fnmatch
import os
from subprocess import Popen, PIPE

dir_path = os.path.dirname(os.path.realpath(__file__))


def main():
    cmd_template = 'dwebp {} -o {}'
    src_dir = '{}/webp'.format(dir_path)
    dest_dir = '{}/png'.format(dir_path)
    webp_files = list_dir(src_dir, '*.webp')
    for file in webp_files:
        src_file = "{}/{}".format(src_dir, file)
        dest_file = '{}/{}.png'.format(dest_dir, file)
        cmd = cmd_template.format(src_file, dest_file)
        print('executing command: %s' % cmd)
        exe_local_simple_cmd(cmd)


def list_dir(dir, pattern):
    '''
    list dir files matches pattern
    :param dir: directory
    :param pattern: pattern, such as '*.webp'
    :return: file name list
    '''
    matched_files = []
    for file in os.listdir(dir):
        if fnmatch.fnmatch(file, pattern):
            print(file)
            matched_files.append(file)
    return matched_files


def exe_local_simple_cmd(cmd):
    """
    execute a command in local
    :param cmd: command
    :return: stdout and stderr
    """
    return Popen(cmd.split(), stdout=PIPE).communicate()


if __name__ == '__main__':
    main()
